//
//  CustomAListLookupController.m
//  MClient
//
//  Created by  wangfei on 10-4-6.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CustomAListLookupController.h"
#import "MClientAppDelegate.h"
#import "MServerDAO.h"
#import "QueryController.h"
#import "EditFormController.h"
#import "MCUIToolkit.h"
#import "CustomFormController.h"

@interface CustomAListLookupController (Private)
- (Boolean)isMultiSelect;
- (void)initMultiItems:(NSString *)aValue label:(NSString *)aLabel;
- (void)initSingleItem:(NSString *)aValue label:(NSString *)aLabel;
@end


@implementation CustomAListLookupController

@synthesize dataObjectName;
@synthesize layoutName;
@synthesize queryFilter;
@synthesize page;
@synthesize listData;
@synthesize listLayout;
@synthesize fieldData;
@synthesize valueField;
@synthesize field;
@synthesize datas;
@synthesize fieldName;
@synthesize lookupBackFills;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
		
	self.title = [listLayout objectForKey:@"lbl"];
	cellWidth = self.width;
	cellHeight = 0.0;
	imageWidth = 0.0;
	imageHeight = 0.0;
	imagesCache = [[NSMutableDictionary alloc] init];

	pageBar = [MCUIToolkit getPageBar:[MCUIToolkit hasQueryField:listLayout] delegate:self];
	pageBar.frame = CGRectMake(0, self.height-nToolBarHeight, self.width, nToolBarHeight);
	pageBar.autoresizingMask = nMCViewAutoresizingMask;
	[self.clientView addSubview:pageBar];
	
	self.tableview.backgroundColor = [UIColor clearColor];
	self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
	self.tableview.frame = CGRectMake(0, 0, self.width, self.height-pageBar.frame.size.height);
	
	if ([self isMultiSelect]) {
		[self rightBarButton:@"确定" withStyle:UIBarButtonItemStyleDone selector:@selector(selectAction:)];
		[self initMultiItems:[self.fieldData objectForKey:@"value"] label:[self.fieldData objectForKey:@"lbl"]];
	}
	else {
		[self initSingleItem:[self.fieldData objectForKey:@"value"] label:[self.fieldData objectForKey:@"lbl"]];
	}
	// 根据配置显示/隐藏帮助按钮
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter05-03-05.html";
	aListInfo = [[NSMutableDictionary alloc] init];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	
	//tableview.frame = CGRectMake(0, 0, self.width, self.height-nToolBarHeight);
	//pageBar.frame = CGRectMake(0, self.height-nToolBarHeight, self.width, nToolBarHeight);
}

- (void)dealloc {
	[pageBar release];
	[dataObjectName release];
	[layoutName release];
	[queryFilter release];
	[listData release];
	[listLayout release];
	[labelBufferArray release];
	[valueBufferArray release];
	[fieldData release];
	[valueField release];
	[field release];	
	[datas release];
	[fieldName release];
	[lookupBackFills release];
	[aListInfo release];
	[imagesCache release];
    [super dealloc];
}

#pragma mark ---UIToolbar事件---
-(void)goFirst:(id)inSender {
	if (page != 1) {
		page = 1;
		[self getDataFromServer];
	}
}

-(void)goPrevious:(id)inSender {
	if (page > 1) {
		page = page - 1;
		[self getDataFromServer];
	}
}

-(void)goNext:(id)inSender {
	if (page < totalPage) {
		page = page + 1;
		[self getDataFromServer];
	}
}

-(void)goLast:(id)inSender {
	if (page != totalPage) {
		page = totalPage;
		[self getDataFromServer];
	}
}

-(void)gotoPage:(id)inSender {
	UITextField *inputView = (UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1];
	int goPage = [inputView.text intValue];
	if (goPage >= 1 && goPage <= totalPage) {
		page = goPage;
		[self getDataFromServer];
	}
}

-(void)reload:(id)inSender {
	[self getDataFromServer];
}

-(void)search:(id)inSender {
	
	QueryController *queryController = [[QueryController alloc] initWithStyle:UITableViewStylePlain];
	queryController.listLayout = self.listLayout;
	queryController.queryFilter = self.queryFilter;
	[self.navigationController pushViewController:queryController animated:YES];
	[queryController release];
}

#pragma mark ---- 数据加载方法 ----
- (void)getDataFromServer {
	[(UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1] resignFirstResponder];
	[imagesCache removeAllObjects];
	[[MServerDAO sharedInstance] getCustomListAsync:layoutName
										queryFilter:queryFilter
											   page:[NSString stringWithFormat:@"%d", page]
										otherParams:[[NSMutableDictionary alloc] init]
										   delegate:self];		
}

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	self.listLayout = returnValue;
	listData = [[NSMutableDictionary alloc] init];
	
	NSMutableArray *recordList = [NSMutableArray array];
	if ([listLayout objectForKey:@"rl"]) {
		recordList = [listLayout objectForKey:@"rl"];
	}
	[self.listData setObject:recordList forKey:@"rl"];
	
	NSMutableArray *buttons = [NSMutableArray array];
	if ([listLayout objectForKey:@"btn"]) {
		buttons = [listLayout objectForKey:@"btn"];
	}
	[self.listData setObject:buttons forKey:@"btn"];
	
	totalPage = 1;
	if ([self.listLayout objectForKey:@"tp"]) {
		totalPage = [[self.listLayout objectForKey:@"tp"] intValue];
	}
	if (totalPage == 0) {
		totalPage = 1;
	}
	if ([pageBar.items count] > 5) {
		UITextField *inputView = (UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1];
		inputView.text = @"";
		inputView.placeholder = [NSString stringWithFormat:@"%d", page];
		UILabel *pageLabel = (UILabel *)(UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:2];
		pageLabel.text = [NSString stringWithFormat:@"/%d", totalPage];
	}
	NSMutableArray *listFields = [listLayout objectForKey:@"item"];
	if ([[listData objectForKey:@"rl"] count] > 0) {
		NSMutableDictionary *record = [[listData objectForKey:@"rl"] objectAtIndex:0];
		for (int i = 0; i < [listFields count]; i++) {
			NSMutableDictionary *appItem = [listFields objectAtIndex:i];
			if ([[appItem objectForKey:@"v"] boolValue]) {
				NSString *fieldType = [MCUIToolkit getFieldType:appItem];
				NSString *name = [MCUIToolkit getFieldName:appItem];
				NSMutableDictionary *fieldSData = [[record objectForKey:@"data"] objectForKey:name];
				if ([fieldType isEqualToString:@"S"]) {
					imageWidth = nImageWidthOfCell;
					imageHeight = nImageHeightOfCell;
					NSMutableDictionary *style = [fieldSData objectForKey:@"style"];
					if (nil != style) {
						if ([style objectForKey:@"width"]) {
							imageWidth = [[style objectForKey:@"width"] floatValue];
						}
						if ([style objectForKey:@"height"]) {
							imageHeight = [[style objectForKey:@"height"] floatValue];
						}
					}
					if (imageWidth > self.width) {
						imageHeight = self.width * imageHeight / imageWidth;
						imageWidth = self.width;
					}
					cellWidth = self.width - imageWidth;
				}
			}
		}
	}
	[self.tableview reloadData];	
}

#pragma mark ---- UITableView处理方法 ----
//TableView的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSMutableArray *recordList = [self.listData objectForKey:@"rl"];
	return [recordList count];
}

//每一行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	int row = [indexPath row];
	
	NSMutableArray *cellInfos = [MCUIToolkit getAListInfo:listLayout
												 listData:[self.listData objectForKey:@"rl"]
												 rowIndex:row
												cellWidth:cellWidth];
	[aListInfo setObject:cellInfos forKey:[NSNumber numberWithInt:row]];
	if ([cellInfos count] <= 0) {
		return 0.0;
	}
	cellHeight = [[[cellInfos objectAtIndex:([cellInfos count] - 1)] objectForKey:@"cellHeight"] floatValue];
	if (cellHeight < imageHeight) {
		cellHeight = imageHeight + 12.0;
		return cellHeight;
	}
	if (cellHeight == 0.0) {
		return cellHeight;
	}
	if (cellHeight < 28.0) {
		return 44.0;
	}
	return cellHeight + 6.0;
}

//初始化TableVie根据参数和数据绘制每一行以及填充数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	int row = [indexPath row];
	UITableViewCell *cell = [MCUIToolkit getAListCell:[aListInfo objectForKey:[NSNumber numberWithInt:row]]
										  imagesCache:imagesCache
											 rowIndex:row
										isMultiSelect:YES
											cellWidth:cellWidth
										   cellHeight:cellHeight
										   imageWidth:imageWidth
										  imageHeight:imageHeight];
	NSMutableDictionary *record = [[self.listData objectForKey:@"rl"] objectAtIndex:row];
	for (int i = 0; i < [valueBufferArray count]; i++) {
		NSString *key = [valueBufferArray objectAtIndex:i];
		if ([[record objectForKey:@"key"] isEqualToString:key]) {
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
			break;
		}
	}
	return cell;
}

//相应用户选中
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath {
	int row = [newIndexPath row];
	
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:newIndexPath];
	NSMutableDictionary *record = [[self.listData objectForKey:@"rl"]objectAtIndex:row];
	if ([self isMultiSelect]) {
		bool selectFlag = YES;
		for (int i = 0; i < [valueBufferArray count]; i++) {
			NSString *key = [valueBufferArray objectAtIndex:i];
			if ([[record objectForKey:@"key"] isEqualToString:key]) {
				[valueBufferArray removeObjectAtIndex:i];
				[labelBufferArray removeObjectAtIndex:i];
				selectFlag = NO;
				break;
			}
		}
		if (selectFlag) {
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
			[valueBufferArray addObject:[record objectForKey:@"key"] == nil?@"":[record objectForKey:@"key"]];
			[labelBufferArray addObject:[record objectForKey:@"desc"] == nil?@"":[record objectForKey:@"desc"]];
		}else {
			cell.accessoryType = UITableViewCellAccessoryNone;
		}	
	}else {
		valueBufferArray = [[NSMutableArray alloc] init];
		labelBufferArray = [[NSMutableArray alloc] init];		
		[valueBufferArray addObject:[record objectForKey:@"key"] == nil?@"":[record objectForKey:@"key"]];
		[labelBufferArray addObject:[record objectForKey:@"desc"] == nil?@"":[record objectForKey:@"desc"]];

		NSString *valueString = [valueBufferArray objectAtIndex:0];
		NSString *labelString = [labelBufferArray objectAtIndex:0];
		
		[self.fieldData setObject:valueString forKey:@"value"];
		[self.fieldData setObject:labelString forKey:@"lbl"];
		self.valueField.text = labelString;
		
		NSMutableDictionary *fieldLabelData = [NSMutableDictionary dictionary];
		[fieldLabelData setObject:labelString forKey:@"value"];
		[datas setObject:fieldLabelData forKey:[@"__" stringByAppendingString:fieldName]];
		
		UIViewController *editFormController = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
		if ([editFormController isKindOfClass:[EditFormController class]] || [editFormController isKindOfClass:[CustomFormController class]]) {
			if (lookupBackFills != nil) {
				for(int k = 0; k<[lookupBackFills count]; k++){
					NSMutableDictionary *lookupBackFill = [lookupBackFills objectAtIndex:k];
					NSString *name = [lookupBackFill objectForKey:@"bf"];
					NSMutableDictionary *recordData = [record objectForKey:@"data"];
					if (recordData == nil) {
						recordData = [[NSMutableDictionary alloc] init];
					}
					NSMutableDictionary *fieldDataLookupBack = [recordData objectForKey:name];
					if(fieldDataLookupBack == nil)
						fieldDataLookupBack = [[NSMutableDictionary alloc] init];
					if ([editFormController isKindOfClass:[EditFormController class]]) {
						[(EditFormController*)editFormController setLookupBackFillByFieldName: [lookupBackFill objectForKey:@"fld"] fieldDataLookupBack:fieldDataLookupBack];	
					} else if ([editFormController isKindOfClass:[CustomFormController class]]) {
						[(CustomFormController*)editFormController setLookupBackFillByFieldName: [lookupBackFill objectForKey:@"fld"] fieldDataLookupBack:fieldDataLookupBack];
					}
				}
			}
			if ([editFormController isKindOfClass:[EditFormController class]])
				[(EditFormController*)editFormController doCalcAction:((MCTextField*)valueField.control)];
		}
		[self.navigationController popViewControllerAnimated:YES];
	}
	[tableView deselectRowAtIndexPath:newIndexPath animated:YES];
}


//导航栏上动作按钮的点击事件
- (void) selectAction: (id) sender {
	@try {
		NSString *labelString = @"";
		NSString *valueString = @"";
		for(int i = 0;i<[valueBufferArray count]; i++) {
			valueString = [valueString stringByAppendingFormat:@"%@,",[valueBufferArray objectAtIndex:i]];
			labelString = [labelString stringByAppendingFormat:@"%@,",[labelBufferArray objectAtIndex:i]];
		}
		if ([labelString length] > 0) {
			labelString = [labelString substringToIndex:[labelString length] - 1];
			valueString = [valueString substringToIndex:[valueString length] - 1];
		}
		[self.fieldData setObject:valueString forKey:@"value"];
		[self.fieldData setObject:labelString forKey:@"lbl"];
		self.valueField.text = labelString;
		
		NSMutableDictionary *fieldLabelData = [NSMutableDictionary dictionary];
		[fieldLabelData setObject:labelString forKey:@"value"];
		[datas setObject:fieldLabelData forKey:[@"__" stringByAppendingString:fieldName]];
		
		[self.navigationController popViewControllerAnimated:YES];		
	}
	@catch (NSException * e) {
		[[MCErrorManagement instance] doError:@"99" 
								returnMessage:[NSString stringWithFormat:@"main: Caught %@: %@", [e name], [e reason]]];		
	}
}

- (void)initMultiItems:(NSString *)aValue label:(NSString *)aLabel {
	labelBufferArray = [[NSMutableArray alloc] init];
	valueBufferArray = [[NSMutableArray alloc] init];
	if (aValue == nil || [aValue isEqualToString:@""]) {
		return;
	}
	
	NSMutableArray *values = [[NSMutableArray alloc] initWithArray:[aValue componentsSeparatedByString:@","]];
	for(int i = 0; i < [values count];i++) {
		if (i == 0 || i == [values count] - 1) {
			if ([[values objectAtIndex:i] isEqualToString:@""]) {
				continue;
			}
		}
		[valueBufferArray addObject:[values objectAtIndex:i]];
	}
	if (aLabel != nil && ![aLabel isEqualToString:@""]) {
		NSMutableArray *labels = [[NSMutableArray alloc] initWithArray:[aLabel componentsSeparatedByString:@","]];
		for(int i = 0; i < [labels count]; i++) {
			[labelBufferArray addObject:[labels objectAtIndex:i]];
		}	
	}
	int count = [valueBufferArray count] - [labelBufferArray count];
	if (count > 0) {
		for (int i = 0; i < count; i++) {
			NSString *value = [[valueBufferArray objectAtIndex:i] copy];
			[labelBufferArray addObject:value];
		}
	}else if (count < 0) {
		for (int i = -count-1; i >= 0; i--) {
			[labelBufferArray removeObjectAtIndex:i];
		}
	}
}

- (void)initSingleItem:(NSString *)aValue label:(NSString *)aLabel {
	valueBufferArray = [[NSMutableArray alloc] init];
	labelBufferArray = [[NSMutableArray alloc] init];
	if (aValue != nil && ![aValue isEqualToString:@""]) {
		[valueBufferArray addObject:aValue];
		[labelBufferArray addObject:aLabel == nil?@"":aLabel];
	}
}

- (Boolean)isMultiSelect {
	NSString *fieldType = [field objectForKey:@"type"];
	if ([fieldType isEqualToString:@"U"]) {
		return YES;
	}
	return NO;
}

@end
